using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace Workflows.Components
{
    /// <summary></summary>
    public class GlobalVariablesConverter : ExpandableObjectConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if(sourceType==typeof(string))
                return true;
            
            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if(destinationType==typeof(string))
                return true;
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string serializedVars = value as string;
            if (string.IsNullOrEmpty(serializedVars))
                return base.ConvertFrom(context, culture, value);

            string[] items = serializedVars.Split(new char[';']);
            Dictionary<string,string> vars=new Dictionary<string, string>();
            foreach(string item in items)
            {
                string[] pair = item.Split(new char['=']);
                if(pair.Length==2)
                {
                    string itemName = pair[0];
                    string itemValue = pair[1];
                    if(!vars.ContainsKey(itemName))
                    {
                        vars.Add(itemName,itemValue);
                    }
                }
            }
            return vars;
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if(value !=null && value.GetType()==typeof(Dictionary<string,object>))
            {
                Dictionary<string, object> globalVars = (Dictionary<string, object>) value;
                StringBuilder buffer=new StringBuilder();
                if (globalVars.Count > 0)
                {
                    string[] keys=new string[globalVars.Count];
                    globalVars.Keys.CopyTo(keys, 0);
                    for (int i = 0; i < keys.Length; i++)
                    {
                        string itemValue = globalVars[keys[i]].ToString();
                        buffer.Append(keys[i] + "=" + itemValue);
                        if(i<keys.Length -1)
                        {
                            buffer.Append(";");
                        }
                    }
                }
                return buffer.ToString();
            }
            else 
                return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}
